<template>
  <view>
    <!-- 用户列表 -->
    <view class="main-container">
      <view class="top-tab-bar">
        <view
          @click="tabClick(item, index)"
          :key="index"
          :class="current === item.value ? 'tab-item-selected' : ''"
          class="tab-item"
          v-for="(item, index) in tabs">
          {{ item.name }}
        </view>
      </view>
    </view>
    <view class="order-list">
      <view class="order-card" v-for="(item, index) in list" :key="index">
        <view class="title-and-status">
          <view class="title-left">
            <view class="title-main">
              {{ item.serverCode }}
            </view>
            <view class="subhead">
              {{ item.serverValue }}
            </view>
          </view>
          <view class="status" style="font-weight: 700">{{ item.status }}</view>
        </view>
        <!-- <view class="item-tag">
          <view v-for="(service, idx) in item.serverValueList" :key="idx">
            <view class="service-tag">
              {{ service }}
            </view>
          </view>
        </view> -->
        <view class="cycle-and-price" style="width: 100%">
          <view class="cycle">
            服务周期：{{ item.serverStart }} -- {{ item.serverEnd }}
          </view>
          <view class="price">￥{{ item.orderAmout }}</view>
        </view>
        <!-- <view class="div-line"></view> -->
        <view class="service-btn">
          <view
            class="my-btn"
            @click="editHandle(item)"
            v-if="item.orderState == 0 && roles == 1000">
            修改
          </view>
          <view
            class="my-btn"
            v-if="item.orderState == 0 && roles == 1000"
            @click="cancelOrderHandle(item)">
            取消
          </view>
          <view
            class="my-btn"
            v-if="
              (item.orderState == 7 || item.orderState == 6.1) && roles == 1000
            "
            @click="delOrderHandle(item)">
            删除
          </view>
          <view
            class="my-btn btn-green"
            @click="toPay(item)"
            v-if="['1', '2'].includes(item.orderState) && roles == 1000">
            立即支付
          </view>
          <view
            class="my-btn"
            v-if="['4'].includes(item.orderState) && roles == 1000"
            @click="endOrderHandle(item)">
            结束服务
          </view>
          <view
            class="my-btn btn-green"
            v-if="['3', '4'].includes(item.orderState) && roles == 1000"
            @click="refundHandle(item)">
            申请退款
          </view>
        </view>
      </view>
    </view>
    <uni-load-more :status="status"></uni-load-more>
    <!-- 取消 -->
    <u-popup
      :show="show"
      @close="closeCancelPopup"
      @open="openCancelPopup"
      lock-scroll
      :overlayStyle="{ touchAction: 'none' }">
      <view class="title-view">
        <view class="title">取消订单</view>
        <view class="subTitle">订单取消后，优惠券可退回，请在有效期内使用</view>
      </view>
      <view style="margin: 0 40rpx">
        <u--form labelPosition="top" :model="model" :rules="rules" ref="uForm">
          <u-form-item
            labelWidth="300"
            label="请选择取消原因"
            prop="cancelInfo.cancelReason">
            <u-radio-group
              iconPlacement="right"
              placement="column"
              v-model="radiovalue"
              @change="groupChange">
              <u-radio
                class="custom-radio"
                activeColor="rgb(25, 190, 107)"
                v-for="(item, index) in radiolist"
                :key="index"
                :label="item.name"
                :name="item.name"
                :customStyle="{ marginBottom: '8px' }"></u-radio>
            </u-radio-group>
          </u-form-item>
        </u--form>
      </view>
      <view class="bottom-view">
        <u-button
          :customStyle="{ width: '280rpx' }"
          shape="circle"
          text="暂不取消"
          @click="closeCancelPopup()"></u-button>
        <u-button
          :customStyle="{ width: '280rpx' }"
          @click="cancelConfirm"
          type="primary"
          shape="circle"
          text="确定取消"></u-button>
      </view>
    </u-popup>
  </view>
</template>

<script>
import PageInfo from "../../utils/pageutils.js";
import {
  orderList,
  orderDetail,
  payOrder,
  payCompanionOrder,
  paymentMessage,
  cancelOrder,
  delOrder,
  endOrder,
} from "../../common/api/index.js";
import { subscribeMessage } from "../../utils/index.js";
export default {
  props: {
    isInIndex: false,
  },
  components: {},
  data() {
    return {
      tabs: [],
      current: 8,
      status: "",
      readForm: {},
      list: [],
      pageInfo: new PageInfo(),
      roles: "",
      radiolist: [
        {
          name: "价格太贵",
          disabled: false,
        },
        {
          name: "服务选错",
          disabled: false,
        },
        {
          name: "服务周期/服务时长选错",
          disabled: false,
        },
        {
          name: "对护工不满意",
          disabled: false,
        },
        {
          name: "不需要了",
          disabled: false,
        },
        {
          name: "其他原因",
          disabled: false,
        },
      ],
      show: false,
      radiovalue: "",
      cancelInfo: {
        orderId: "",
        cancelReason: "",
      },
      model: {
        cancelInfo: {
          orderId: "",
          cancelReason: "",
        },
      },
      rules: {
        "cancelInfo.cancelReason": {
          type: "string",
          required: true,
          message: "请选择取消原因",
          trigger: ["change"],
        },
      },
      orderDetail: {},
      uid: "",
    };
  },
  onPullDownRefresh() {
    this.refresh();
  },
  onReachBottom() {
    this.loadMore();
  },
  mounted() {
    this.refresh();
  },
  onShow() {
    this.refresh();
  },
  methods: {
    sendMsg() {
      subscribeMessage({
        openId: uni.getStorageSync("openid_key"),
        templateId: "1p7Z_SSvpsYroEhNz9OKedmie1bnUwzkx3XvgYD2mDg",
        uid: this.uid,
      });
    },
    tabClick(item, index) {
      this.current = item.value;
      this.refresh();
    },
    // 列表
    getList() {
      let userId = uni.getStorageSync("USER_ID");
      this.roles = uni.getStorageSync("ROLES");
      let params = {
        pageIndex: this.pageInfo.pageIndex,
        pageSize: this.pageInfo.pageSize,
        nurseUserId: userId,
        orderState: this.current,
        roles: this.roles,
        orderState: this.current,
      };
      orderList(params)
        .then((result) => {
          const list = result.data.rows || [];
          const total = result.data.total;
          this.list = [...this.list, ...list];
          this.pageInfo.total = total;
          this.pageInfo.loadedTotal = this.list.length;
          setTimeout(() => {
            if (this.pageInfo.isNotLoadAll) {
              this.status = "more";
            } else {
              this.status = "noMore";
            }
            uni.stopPullDownRefresh();
          }, 200);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 编辑
    editHandle(item) {
      this.orderDetail = item;
      uni.navigateTo({
        url: `/nursingWorkerPages/pages/payConfirm/payConfirm?orderId=${item.orderId}&isUpdate=true`,
      });
    },
    refresh() {
      this.pageInfo.reset();
      this.list = [];
      this.status = "loading";
      this.getList();
    },
    loadMore() {
      if (this.pageInfo.isNotLoadAll) {
        this.status = "loading";
        this.pageInfo.nextPage();
        this.getList();
      } else {
        this.status = "noMore";
      }
    },
    toPay(item) {
      this.orderDetail = item;
      console.log("进来了", item);
      this.uid = item.orderId;
      if (item.serverCode === "医院陪护") {
        let params = {
          companionVisitAmout: item.orderAmout,
          openId: uni.getStorageSync("openid_key"),
          companionVisitNum: item.orderNumber,
        };
        payCompanionOrder(params)
          .then((res) => {
            if (res.data.code == 200) {
              this.pay(res.data.data);
            }
          })
          .catch((error) => {
            console.log(error);
          });
      } else {
        let params = {
          orderCategory: item.orderCategory,
          orderServer: item.orderServer,
          orderAmout: item.orderAmout,
          nursePatientId: item.nursePatientId,
          nurseUserId: item.nurseUserId,
          serverStart: item.serverStart,
          serverEnd: item.serverEnd,
          orderId: item.orderId,
          isFlag: 1,
          openId: uni.getStorageSync("openid_key"),
          orderNumber: item.orderNumber,
        };
        payOrder(params)
          .then((res) => {
            if (res.data.code == 200) {
              this.pay(res.data.data);
            }
          })
          .catch((error) => {
            console.log(error);
          });
      }
    },
    pay(result) {
      // this.sendMsg();
      let that = this;
      const data = result;
      const orderInfo = {
        appid: data.appid, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
        nonceStr: data.nonceStr, // 随机字符串
        package: data.package, // 固定值
        timeStamp: data.timeStamp, // 时间戳（单位：秒）
        paySign: data.paySign, // 签名，这里用的 MD5/RSA 签名
        signType: data.signType,
      };
      uni.requestPayment({
        provider: "wxpay",
        ...orderInfo,
        success(res) {
          // console.log("支付成功", res);
          uni.showModal({
            icon: "success",
            title: "提示",
            content: "支付成功！",
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                that.sendMsg();
                this.getList();
              }
              // setTimeout(() => {
              //   uni.navigateBack();
              // }, 2000);
            },
          });
        },
        fail(err) {
          console.log("支付失败", err);
          uni.showToast({
            icon: "none",
            title: "支付失败",
          });
        },
      });
    },
    openCancelPopup() {
      this.show = true;
    },
    closeCancelPopup() {
      this.show = false;
    },
    groupChange(n) {
      this.cancelInfo.cancelReason = n;
      this.radiovalue = n;
      this.model.cancelInfo.cancelReason = n;
    },
    cancelOrderHandle(item) {
      this.orderDetail = item;
      this.openCancelPopup();
      this.cancelInfo.orderId = item.orderId;
    },
    cancelConfirm() {
      let that = this;
      this.$refs.uForm.validate().then((valid) => {
        if (valid) {
          cancelOrder({
            orderId: this.cancelInfo.orderId,
            orderCancel: this.cancelInfo.cancelReason,
          })
            .then((res) => {
              let data = res.data;
              if (data.code == 200) {
                uni.showToast({
                  icon: "success",
                  title: data.msg,
                });
              }
            })
            .finally(() => {
              that.radiovalue = "";
              that.closeCancelPopup();
              that.refresh();
            });
        }
      });
    },
    delOrderHandle(item) {
      this.orderDetail = item;
      let that = this;
      uni.showModal({
        title: "提示",
        content: "确定删除？",
        showCancel: true,
        cancelText: "取消",
        confirmText: "确定",
        success: function (res) {
          if (res.confirm) {
            delOrder({ orderId: item.orderId })
              .then((res) => {
                if (res.code == 200) {
                  uni.showToast({
                    icon: "success",
                    title: res.msg,
                  });
                }
              })
              .finally(() => {
                that.refresh();
              });
          }
        },
      });
    },
    refundHandle(item) {
      this.orderDetail = item;
      if (item.serverCode === "医院陪诊") {
        uni.navigateTo({
          url: `/nursingWorkerPages/pages/refund/CompaionRefund?orderId=${item.orderId}&orderState=${item.orderState}`,
        });
      } else {
        uni.navigateTo({
          url: `/nursingWorkerPages/pages/refund/refund?orderId=${item.orderId}&orderState=${item.orderState}`,
        });
      }
    },
    // 结束订单
    endOrderHandle(item) {
      let that = this;
      uni.showModal({
        title: "提示",
        content: "确定结束？",
        showCancel: true,
        cancelText: "取消",
        confirmText: "确定",
        success: function (res) {
          if (res.confirm) {
            endOrder({ orderId: item.orderId })
              .then((result) => {
                if (result.data.code == 200) {
                  uni.showToast({
                    icon: "success",
                    title: result.data.msg,
                  });
                }
              })
              .finally(() => {
                that.refresh();
              });
          }
        },
      });
    },
  },
};
</script>
<style>
page {
  background-color: #f5f5f5;
}
</style>
<style lang="scss" scoped>
page {
  background: #f9f9f9;
}

.main-container {
  display: flex;
  flex-direction: column;
}

.top-tab-bar {
  padding: 20rpx 30rpx;
  box-sizing: border-box;
  display: grid;
  grid-template-columns: repeat(auto-fit, 150rpx);
  grid-template-rows: repeat(auto-fit, 66rpx);
  grid-column-gap: 20rpx;
  grid-row-gap: 26rpx;
  background: #f9f9f9;

  // position: sticky;
  // top: 0;
  // z-index: 2;
  .tab-item {
    width: 150rpx;
    height: 66rpx;
    background: #f1f1f1;
    border-radius: 32rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: rgba(35, 35, 35, 0.8);
    font-size: 26rpx;
  }

  .tab-item-selected {
    background: #dff0ef;
    color: #0bc5ae;
  }
}

.order-card {
  margin-right: 30rpx;
  margin-left: 30rpx;
  background: white;
  padding: 30rpx;
  box-sizing: border-box;
  border-radius: 16rpx;
  margin-top: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .title-and-status {
    display: flex;
    width: 100%;
    justify-content: space-between;
    align-items: flex-start;

    .title-left {
      display: flex;
      justify-content: flex-start;
      width: 76%;
      align-items: flex-start;

      .title-main {
        width: 200rpx;
        color: #333333;
        font-size: 35rpx;
        font-weight: 700;
        margin-right: 10rpx;
      }

      .subhead {
        color: #747474;
        font-size: 28rpx;
        width: 100%;
      }
    }

    .time {
      flex: 1;
      color: rgba(35, 35, 35, 0.7);
      font-size: 26rpx;
    }

    .status {
      font-size: 28rpx;
      color: #747474;
      font-weight: 700;
    }
  }

  .item-tag {
    display: flex;
    justify-content: flex-start;
    // width: 80%;
    align-items: center;
    margin-top: 20rpx;
    flex-wrap: wrap;

    .service-tag {
      min-width: 110rpx;
      background-color: #eafaf5;
      font-size: 20rpx;
      color: #6f7070;
      padding: 10rpx;
      height: 50rpx;
      line-height: 30rpx;
      text-align: center;
      border-radius: 25rpx;
      margin-right: 10rpx;
      margin-bottom: 10rpx;
    }
  }

  .cycle-and-price {
    display: flex;
    justify-content: space-between;
    font-size: 25rpx;
    color: #6c6c6c;
    margin-top: 10rpx;

    .cycle {
      width: 80%;
    }

    .price {
    }
  }

  .project-row {
    display: flex;
    align-items: center;
    margin-top: 36rpx;

    .img {
      width: 136rpx;
      height: 136rpx;
      border-radius: 20rpx;
    }

    .name {
      color: #232323;
      font-size: 32rpx;
      font-weight: bold;
      margin-left: 24rpx;
    }
  }

  .info-row {
    display: flex;
    margin-top: 40rpx;

    .name {
      width: 136rpx;
      color: rgba(35, 35, 35, 0.7);
      font-size: 26rpx;
    }

    .value {
      color: #232323;
      font-size: 26rpx;
    }
  }

  .div-line {
    width: 100%;
    height: 2rpx;
    background: #f8f8f8;
    margin-top: 40rpx;
  }

  .price-and-pay {
    display: flex;
    align-items: center;
    margin-top: 20rpx;

    .left {
      display: flex;
      align-items: center;
      flex: 1;
    }

    .cancel-btn {
      width: 150rpx;
      height: 60rpx;
      border: solid 2rpx rgba(35, 35, 35, 0.26);
      border-radius: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      color: rgba(35, 35, 35, 0.8);
      font-size: 26rpx;
      margin-left: 8rpx;
      margin-right: 8rpx;
    }

    .ok-btn {
      width: 150rpx;
      height: 60rpx;
      border: solid 2rpx #0bc5ae;
      border-radius: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #0bc5ae;
      font-size: 26rpx;
      margin-left: 8rpx;
      margin-right: 8rpx;
    }
  }
}

.del-btn {
  width: 60rpx;
  height: 40rpx;
  border: solid 2rpx #c5070a;
  border-radius: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c5070a;
  font-size: 14rpx;
  margin-left: 8rpx;
  margin-right: 8rpx;
}

.service-btn {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-top: 40rpx;
  flex-wrap: wrap;
  padding-right: 50rpx;
}

.service-btn .my-btn:not(:last-child) {
  margin-right: 10rpx;
}

.my-btn {
  min-width: 140rpx;
  height: 58rpx;
  line-height: 58rpx;
  border: 1rpx solid #d0d0d0;
  border-radius: 40rpx;
  color: #787878;
  text-align: center;
}

.btn-green {
  border-color: #04bdb3;
  color: #04bdb3;
}

.title-view {
  position: relative;
  display: flex;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  width: 100%;
  padding: 20rpx 0;

  .title {
    color: #232323;
    font-size: 32rpx;
    font-weight: bold;
  }

  .subTitle {
    font-size: 28rpx;
    margin-top: 15rpx;
  }
}

// 取消弹窗
.bottom-view {
  width: 100%;
  padding: 30rpx;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
}

.custom-style {
  width: 120rpx !important;
}

.custom-radio {
  padding: 20rpx 0 !important;
}
</style>
